using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

public class UcComboBox2 : ComboBox
{
    // 字段
    private Color _normalBorderColor = Color.Red;
    private Color _focusedBorderColor = Color.Green;
    private Color _currentBorderColor;
    private int _borderThickness = 3;

    // 正常状态边框颜色
    [Category("外观")]
    [Description("获取或设置控件正常状态下的边框颜色")]
    public Color NormalBorderColor
    {
        get => _normalBorderColor;
        set
        {
            _normalBorderColor = value;
            if (!Focused)
            {
                _currentBorderColor = value;
                Invalidate();
            }
        }
    }

    // 获得焦点时的边框颜色
    [Category("外观")]
    [Description("获取或设置控件获得焦点时的边框颜色")]
    public Color FocusedBorderColor
    {
        get => _focusedBorderColor;
        set
        {
            _focusedBorderColor = value;
            if (Focused)
            {
                _currentBorderColor = value;
                Invalidate();
            }
        }
    }

    // 边框厚度
    [Category("外观")]
    [Description("获取或设置控件的边框厚度")]
    [DefaultValue(1)]
    public int BorderThickness
    {
        get => _borderThickness;
        set
        {
            if (value > 0)
            {
                _borderThickness = value;
                Invalidate();
            }
        }
    }

    public UcComboBox2()
    {
        FlatStyle = FlatStyle.Popup;
        DoubleBuffered = true;
        _currentBorderColor = _normalBorderColor; // 初始化为正常状态颜色
    }

    // 重写获得焦点事件
    protected override void OnGotFocus(EventArgs e)
    {
        base.OnGotFocus(e);
        _currentBorderColor = _focusedBorderColor; // 切换到焦点颜色
        Invalidate(); // 重绘控件
    }

    // 重写失去焦点事件
    protected override void OnLostFocus(EventArgs e)
    {
        base.OnLostFocus(e);
        _currentBorderColor = _normalBorderColor; // 恢复正常颜色
        Invalidate(); // 重绘控件
    }

    // 重写绘制方法
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        // 绘制边框
        using (Pen pen = new Pen(_currentBorderColor, _borderThickness))
        {
            // 计算边框位置，考虑边框厚度
            int halfThickness = _borderThickness / 2;
            Rectangle borderRect = new Rectangle(
                halfThickness,
                halfThickness,
                ClientSize.Width - _borderThickness,
                ClientSize.Height - _borderThickness
            );

            e.Graphics.DrawRectangle(pen, borderRect);
        }
    }

    // 处理鼠标点击获取焦点的情况
    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);
        if (!Focused)
        {
            Focus(); // 点击时获取焦点
        }
    }
}
